# -*- coding: utf-8 -*-

import sys
import os
import requests
import json
import time
import re
import traceback,threading

print('>>>正在初始化...')

HTTP_SB_URL = 'http://ydhzcms.bimsheng.com/daping/rest/people/'
proDir = os.path.split(os.path.realpath(__file__))[0]
print('proDir---',proDir)
proDir = proDir.replace('\dist','')
import time
from selenium import webdriver
def loginurl(account='',password='',miniters=300):
    cookie = None
    #创建一个浏览器对象
    browser = webdriver.Firefox(executable_path='C:\\geckodriver')

    profile=webdriver.FirefoxProfile()

    profile.accept_untrusted_certs=True

    geckodriverPath = os.path.join(proDir, "geckodriver")
    browser=webdriver.Firefox(firefox_profile=profile,executable_path=geckodriverPath) 

    # browser = webdriver.Chrome()
    try:
        browser.get('https://pm.scg.cn/SCG/SSO/Login')
        time.sleep(2)
        #定位到账号的输入框
        id_input = browser.find_element_by_xpath('//input[@id="j_username"]')
        time.sleep(2)
        id_input.send_keys(account)
        #定位到密码输入框，输入密码
        pw_input = browser.find_element_by_xpath('//input[@id="j_password"]')
        pw_input.send_keys(password)
        time.sleep(1)
        #点击登录按钮
        browser.find_element_by_xpath('//button[@class="white loginBt"]').click()
        time.sleep(3)
        # try:
        #     tiaoguo = browser.find_element_by_xpath('//a[@id="login-form-cancel"]')
        #     if tiaoguo:
        #         tiaoguo.click()
        # except:
        #     print('无需跳过')
        
        # #获取登录的cookie
        cookie = browser.get_cookies()
        
        cookiearr = []
        for item in cookie:
            cookiearr.append(item['name']+'='+item['value'])
        cookiestr = ';'.join(cookiearr)
        print('cookiestr---',cookiestr)
        # cookie = cookie['name']+'='+cookie['value']
        # time.sleep(3)
        # browser.switch_to.window(browser.window_handles[-1])
        # time.sleep(3)
        # szkb = browser.find_element_by_xpath('//div[text()="企业看板"]')
        # # action_chains.double_click(szkb).perform()
        # szkb.click()
        # time.sleep(3)
        # iframe = browser.find_element_by_xpath('//iframe[contains(@src,"/i8/EPM/MC/EpmMetopeOptions/EpmMetopeShow?AppTitle=%E4%BC%81%E4%B8%9A%E7%9C%8B%E6%9D%BF")]')
        # browser.switch_to.frame(iframe)
        # time.sleep(3)
        # iframe = browser.find_element_by_xpath('//iframe[contains(@src,"/i8//EPM/MC/EpmStatichtml/StatichtmlView?id=139")]')
        # browser.switch_to.frame(iframe)
        # time.sleep(3)
        # iframe = browser.find_element_by_xpath('//iframe[contains(@src,"../page3/projectMap.html?t=")]')
        # browser.switch_to.frame(iframe)
        
        # time.sleep(3)
        # shtsgxm_c = browser.find_element_by_xpath('//div[text()="中国共产党第一次全国代表大会纪念馆"]')
        # shtsgxm_c.click()

        # browser.switch_to_default_content()#切出当前iframe
        # time.sleep(3)
        # iframe = browser.find_element_by_xpath('//iframe[contains(@src,"/i8/EPM/MC/EpmMetopeOptions/EpmMetopeShow?mtype=1&projId=348200211000008&AppTitle=%E9%A1%B9%E7%9B%AE%E6%8C%87%E6%8C%A5%E4%B8%AD%E5%BF%83")]')
        # browser.switch_to.frame(iframe)

        # time.sleep(3)
        # iframe = browser.find_element_by_xpath('//iframe[contains(@src,"/i8//EPM/MC/EpmStatichtml/StatichtmlView?id=140")]')
        # browser.switch_to.frame(iframe)
        
        # ####获取人员信息
        # time.sleep(3)
        # iframe = browser.find_element_by_xpath('//iframe[contains(@src,"../page3/workerRegister.html?t=")]')
        # browser.switch_to.frame(iframe)
        # time.sleep(3)
        # #获取该节点下的所有子节点
        # # jinrijinchu = browser.find_element_by_xpath('//div[contains(text(),"今日进出人次")]').get_attribute('innerHTML')#可行方案
        # jinrijinchu = browser.find_elements_by_class_name('attendance-item-left-item')
        # today_peoples = '0'
        # for item in jinrijinchu:
        #     # print('item---',item.get_attribute('innerHTML'))
        #     leftval = item.get_attribute('innerHTML')
        #     if '今日进出人次' in leftval:
        #         today_peoples = leftval.replace('今日进出人次','').replace(':','')


        # browser.switch_to_default_content()#重新切出当前iframe
        # time.sleep(3)
        # iframe = browser.find_element_by_xpath('//iframe[contains(@src,"/i8/EPM/MC/EpmMetopeOptions/EpmMetopeShow?mtype=1&projId=348200211000008&AppTitle=%E9%A1%B9%E7%9B%AE%E6%8C%87%E6%8C%A5%E4%B8%AD%E5%BF%83")]')
        # browser.switch_to.frame(iframe)

        # time.sleep(3)
        # iframe = browser.find_element_by_xpath('//iframe[contains(@src,"/i8//EPM/MC/EpmStatichtml/StatichtmlView?id=140")]')
        # browser.switch_to.frame(iframe)
        # ####获取进出记录
        # time.sleep(3)
        # iframe = browser.find_element_by_xpath('//iframe[contains(@src,"../page3/ListPanel_shjg.html?source=workerDetail_shjg_data&showMore=true&showDetail=true&showInterval=true&t=")]')
        # browser.switch_to.frame(iframe)
        # time.sleep(3)

        # tb = browser.find_element_by_xpath('//table[@class="table"]/tbody')
        # trlist = tb.find_elements_by_tag_name('tr')
        # churujilu = []
        # for tritem in trlist:
        #     tdlist = tritem.find_elements_by_tag_name('td')
        #     obj = {}
        #     index = 0
        #     for tditem in tdlist:
        #         spanitem = None
        #         try:
        #             spanitem = tditem.find_element_by_tag_name('span')
        #             # print('spanitem----',spanitem.get_attribute('innerHTML'))
        #             spanvalue = spanitem.get_attribute('innerHTML')
        #             svs = spanvalue.split('\n')
        #             spanvalue = svs[-2].strip()
        #             if index==1:
        #                 obj['name'] = spanvalue
        #             elif index==2:
        #                 obj['company'] = spanvalue
        #             elif index==3:
        #                 obj['people_type'] = spanvalue
        #             elif index==4:
        #                 obj['in_time'] = spanvalue
        #             elif index==5:
        #                 obj['out_time'] = spanvalue
        #         except:
        #             # print('找不到该元素')
        #             continue
                
        #         index = index+1
            
        #     churujilu.append(obj)
                
            
        # time.sleep(4)
        # # print('churujilu----',churujilu)
        # today_peoples = today_peoples.split('\n')[-2]
        # print('today_peoples----',today_peoples.strip())
        #发送http请求

        try:
            data = {}
            header = {
                # "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0",
                # "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
                # "Accept-Encoding":"gzip, deflate, br",
                # "Accept-Language":"zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
                # "Connection":"keep-alive",
                # "Host":"pm.scg.cn",
                # "Upgrade-Insecure-Requests":'1',
                "Cookie":cookiestr
            }
            jiekou_url = 'https://pm.scg.cn/i8/PMS/DCS/DcsCommandPortal/GetCompanyYgCheckOut?pcid=348201102000004&limit=40'
            result = json.loads(requests.get(jiekou_url,headers=header).text)
            print(result)
        except Exception as e:
            traceback.print_exc()
            print('发送请求失败')
    
    except:
        traceback.print_exc()
        print('异常处理')
    
    # if browser:
    #     browser.close()
    # return cookie

class MainThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        # config = configparser.ConfigParser()
        
        # configPath = os.path.join(proDir, "config.ini")
        # config.read(configPath)
        # username = config.get('config','username')
        # password = config.get('config','password')
        # miniters = int(config.get('config','miniters'))
        while True:
            try:
                # loginurl(username,password,miniters)
                loginurl('dd651','Xrj888888',60)
                print("线程在跑----")

            except Exception as e:
                print('登录主线程报错，继续执行。。。。')
                traceback.print_exc()
            
            time.sleep(5)
    
import configparser
if __name__ == '__main__':
    print(">>>>>>>>  login")
    
    MainThread().start()
    print('执行成功')
    time.sleep(2)

    
    # try:
    #     loginurl('dd651','Xrj888888',60)
    # except Exception as e:
    #     print('登录主线程报错，继续执行。。。。')
    #     traceback.print_exc()

